package com.my.bigsite.modules.act.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.IdentityLinkType;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.my.bigsite.common.util.Page;
import com.my.bigsite.modules.act.entity.Leave;

/**
 * 请假流程Service
 * 
 * @author HenryYan
 */
@Service
public class LeaveWorkflowService {

	private static Logger logger = LoggerFactory
			.getLogger(LeaveWorkflowService.class);

	// private LeaveManager leaveManager;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;

	@Autowired
	private IdentityService identityService;
	@Autowired
	private ActLeaveService leaveManager;

	/**
	 * 启动流程
	 * 
	 * @param entity
	 */
	public ProcessInstance startWorkflow(Leave entity,
			Map<String, Object> variables) {

		logger.info("save entity: {}", entity);
		String businessKey = entity.getId().toString();

		ProcessInstance processInstance = null;
		try {
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			logger.info("当前申请人保存：" + entity.getUserId());
			identityService.setAuthenticatedUserId(entity.getUserId());

			processInstance = runtimeService.startProcessInstanceByKey(
					"leave-dynamic-from", businessKey, variables);
			String processInstanceId = processInstance.getId();
			entity.setProcessInstanceId(processInstanceId);
			leaveManager.saveLeave(entity);
			logger.info(
					"start process of {key={}, bkey={}, pid={}, variables={}}",
					new Object[] { "leave", businessKey, processInstanceId,
							variables });
		} finally {
			identityService.setAuthenticatedUserId(null);
		}
		return processInstance;
	}

	/**
	 * 查询待办任务
	 * 
	 * @param userId
	 *            用户ID
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Leave> findTodoTasks(String userId, Page<Leave> page,
			int[] pageParams) {
		List<Leave> results = new ArrayList<Leave>();

		// 根据当前人的ID查询
		TaskQuery taskQuery = taskService.createTaskQuery()
				.taskCandidateOrAssigned(userId);
		List<Task> tasks = taskQuery.list();
		// 根据流程的业务ID查询实体并关联
		for (Task task : tasks) {
			String processInstanceId = task.getProcessInstanceId();
			ProcessInstance processInstance = runtimeService
					.createProcessInstanceQuery()
					.processInstanceId(processInstanceId).active()
					.singleResult();
			String businessKey = processInstance.getBusinessKey();
			if (businessKey == null) {
				continue;
			}

			Leave leave = leaveManager.getLeave(new Long(businessKey));
			leave.setTask(task);
			leave.setProcessInstance(processInstance);
			leave.setProcessDefinition(getProcessDefinition(processInstance
					.getProcessDefinitionId()));
			results.add(leave);

		}

		page.setTotalCount(taskQuery.count());
		page.setResult(results);
		return results;
	}

	/**
	 * 查询参与的任务
	 * 
	 * @param userId
	 *            用户ID
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Leave> findTodoTasks2(String userId,
			Page<Leave> page, int[] pageParams) {
		List<Leave> results = new ArrayList<Leave>();
		// 根据当前人的ID查询
		TaskQuery taskQuery = taskService.createTaskQuery().taskInvolvedUser(
				userId);
		List<Task> tasks = taskQuery.list();
		// 根据流程的业务ID查询实体并关联
		for (Task task : tasks) {
			List<IdentityLink> identityLinkList = taskService
					.getIdentityLinksForTask(task.getId());
			if (identityLinkList == null || identityLinkList.size() == 0) {
				continue;
			}
			for (IdentityLink identity : identityLinkList) {
				if (identity.getType().equals(IdentityLinkType.PARTICIPANT)
						&& userId.equals(identity.getUserId())) {
					String processInstanceId = task.getProcessInstanceId();
					ProcessInstance processInstance = runtimeService
							.createProcessInstanceQuery()
							.processInstanceId(processInstanceId).active()
							.singleResult();
					String businessKey = processInstance.getBusinessKey();
					if (businessKey == null) {
						continue;
					}
					Leave leave = leaveManager.getLeave(new Long(businessKey));
					/*
					 * leave.put("task", task); leave.put("processInstance",
					 * processInstance); leave.put("tasktype",
					 * identity.getType()); leave.put("processDefinition",
					 * getProcessDefinition
					 * (processInstance.getProcessDefinitionId()));
					 */leave.setTask(task);
					leave.setProcessInstance(processInstance);
					leave.setProcessDefinition(getProcessDefinition(processInstance
							.getProcessDefinitionId()));
					results.add(leave);
				}
			}

		}


		page.setTotalCount(taskQuery.count());
		page.setResult(results);
		return results;
	}

	/**
	 * 查询流程定义对象
	 * 
	 * @param processDefinitionId
	 *            流程定义ID
	 * @return
	 */
	protected ProcessDefinition getProcessDefinition(String processDefinitionId) {
		ProcessDefinition processDefinition = repositoryService
				.createProcessDefinitionQuery()
				.processDefinitionId(processDefinitionId).singleResult();
		return processDefinition;
	}

}
